<template>
  <basic-container>
    <avue-crud
      ref="crud"
      v-model="form"
      :option="option"
      :table-loading="loading"
      :data="data"
      :page="page"
      :before-open="beforeOpen"
      :before-close="beforeClose"
      :cell-style="cellStyle"
      :row-style="rowStyle"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @row-click="rowClick"
      @refresh-change="refresh"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @on-load="onLoad"
    >
      <!--      <template slot="menuLeft">-->
      <!--        <el-button-->
      <!--          @click="handleDelete"-->
      <!--          type="danger"-->
      <!--          size="small"-->
      <!--          icon="el-icon-delete"-->
      <!--          plain-->
      <!--        >-->
      <!--          删 除-->
      <!--        </el-button>-->
      <!--      </template>-->
      <template slot="menu" slot-scope="{row}">
        <el-button v-if="row.menuType!=3" type="text" icon="el-icon-plus" size="medium" @click.stop="handleAddSubMenu(row)">
          新增
        </el-button>
      </template>
      <template slot="hidden" slot-scope="{row}">
        <el-tooltip :content="'是否隐藏:' + (row.hidden? '隐藏/禁用': '显示/可用')" placement="top">
          <el-tag :type="row.hidden? 'danger':'success'">
            {{ row.hidden? '隐藏/禁用': '显示/可用' }}
          </el-tag>
        </el-tooltip>
      </template>
      <template slot="external" slot-scope="{row}">
        <el-tag :type="row.external? 'danger':'success'">
          {{ row.external? '是': '否' }}
        </el-tag>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import { mapGetters } from 'vuex'
import { isPermissionCode } from '@/util/ValidateUtil'

const addSysMenuAction = 'sys/menu/addSysMenu'
const updateSysMenuAction = 'sys/menu/updateSysMenu'
const removeSysMenuAction = 'sys/menu/removeSysMenu'
const removeSysMenusAction = 'sys/menu/removeSysMenus'
const getSysMenuByIdAction = 'sys/menu/getSysMenuById'
const getSysMenuPageListAction = 'sys/menu/getSysMenuPageList'

const getSysRoleMenuListAction = 'sys/menu/getSysMenuList'
// 图标
const listIconFontIconsAction = 'sys/menu/listIconFontIcons'
const listElementIconsAction = 'sys/menu/listElementIcons'

export default {
  name: 'Menu',
  data () {
    const permissionCode = (rule, value, callback) => {
      // if (!value) {
      //   return callback(new Error('权限标识码不能为空'))
      // }
      if (value && !isPermissionCode(value)) {
        callback(new Error('权限标识码只能是字母者拼音加冒号!'))
      } else {
        callback()
      }
    }
    return {
      addSubMenu: false,
      addSubMenuRow: {},
      menuTypeDicData1: [
        {
          label: '顶部导航',
          value: 1
        },
        {
          label: '侧边菜单/模块',
          value: 2
        },
        {
          label: '按钮/权限',
          value: 3
        }
      ],
      menuTypeDicData2: [
        {
          label: '侧边菜单/模块',
          value: 2
        },
        {
          label: '按钮/权限',
          value: 3
        }
      ],
      data: [],
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        // title: '菜单权限表',
        border: true,
        menu: true,
        menuType: 'text',
        lazy: true,
        tip: true,
        tipPlacement: 'top-start',
        index: true,
        indexLabel: '序号',
        indexFixed: true,
        searchShow: true,
        searchMenuSpan: 5,
        selection: true,
        selectionWidth: 60,
        selectionFixed: false,
        defaultExpandAll: false,
        rowKey: 'id',
        expandRowKeys: ['1', '2'],
        addBtn: true,
        addTitle: '新增菜单',
        viewBtn: false,
        excelBtn: false,
        printBtn: false,
        dialogDrag: true,
        dialogDirection: 'rtl',
        dialogType: 'dialog',
        column: [
          {
            label: '类型',
            prop: 'menuType',
            type: 'radio',
            span: 24,
            width: 160,
            hide: false,
            button: true,
            showColumn: true,
            overHidden: true,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true,
            rules: [{
              required: true,
              message: '请输入菜单,1=顶部导航单,2=侧边菜单,3=按钮',
              trigger: 'blur'
            }],
            dicData: [],
            value: 1
          },
          {
            label: '上级菜单',
            prop: 'pid',
            type: 'tree',
            span: 24,
            hide: true,
            showColumn: false,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true,
            dicData: [],
            props: {
              label: 'menuName',
              value: 'id',
              children: 'children'
            },
            rules: [{
              required: true,
              message: '请选择上级菜单',
              trigger: 'blur'
            }]
          },
          {
            label: '名称',
            prop: 'menuName',
            type: 'input',
            hide: false,
            search: true,
            searchPlaceholder: '请输入菜单名称',
            showColumn: true,
            overHidden: true,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true,
            rules: [{
              required: true,
              message: '请输入菜单名称或按钮权限名称',
              trigger: 'blur'
            }]
          },
          {
            label: '图标',
            prop: 'menuIcon',
            type: 'icon-select',
            hide: false,
            width: 70,
            showColumn: false,
            overHidden: true,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true,
            rules: [{
              required: true,
              message: '请输入菜单图标',
              trigger: 'blur'
            }],
            iconList: [
              {
                label: 'Element图标',
                list: []
              },
              {
                label: 'Iconfont图标',
                list: []
              }
            ]
          },
          {
            label: '路由名称',
            prop: 'componentName',
            type: 'tree',
            hide: false,
            span: 24,
            dicData: [],
            defaultExpandAll: true,
            props: {
              label: 'name',
              value: 'name',
              children: 'children'
            },
            showColumn: false,
            overHidden: true,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true,
            tip: '路由名称对应的是vue router中组件的name属性',
            rules: [{
              required: false,
              message: '请输入路由名称,对应vue router中的name属性',
              trigger: 'blur'
            }]
          },
          {
            label: '显示顺序',
            prop: 'menuOrder',
            type: 'number',
            hide: false,
            width: 80,
            value: 1,
            showColumn: false,
            overHidden: true,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true,
            rules: [{
              required: false,
              message: '请输入显示顺序',
              trigger: 'blur'
            }]
          },
          {
            label: '权限标识',
            prop: 'permission',
            type: 'input',
            hide: false,
            span: 24,
            showColumn: false,
            overHidden: true,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true,
            rules: [{
              required: false,
              validator: permissionCode,
              trigger: 'blur'
            }]
          },
          {
            label: '是否外链',
            prop: 'external',
            type: 'radio',
            hide: false,
            width: 80,
            slot: true,
            showColumn: false,
            overHidden: true,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true,
            rules: [{
              required: false,
              message: '请输入是否为外链（0是 1否）',
              trigger: 'blur'
            }],
            dicData: [
              {
                label: '否',
                value: false
              },
              {
                label: '是',
                value: true
              }
            ],
            value: false
          },
          {
            label: '外链地址',
            prop: 'externalUrl',
            type: 'url',
            hide: true,
            showColumn: false,
            overHidden: true,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true
          },
          {
            label: '是否显示/可用',
            prop: 'hidden',
            type: 'radio',
            hide: false,
            labelWidth: 120,
            showColumn: true,
            overHidden: true,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true,
            slot: true,
            rules: [{
              required: false,
              message: '请选择是否需要显示',
              trigger: 'blur'
            }],
            dicData: [
              {
                label: '显示/可用',
                value: false
              },
              {
                label: '隐藏/禁用',
                value: true
              }
            ],
            value: false
          },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            maxlength: 200,
            span: 24,
            showWordLimit: true,
            hide: true,
            showColumn: false,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true
          }
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['permissions', 'website']),
    ids () {
      const ids = []
      this.selectionList.forEach((e) => {
        ids.push(e.id)
      })
      return ids
    }
  },
  watch: {
    'form.menuType': {
      handler (newValue, oldValue) {
        const pidIndex = this.$refs.crud.findColumnIndex('pid')
        const componentNameIndex = this.$refs.crud.findColumnIndex('componentName')
        const menuIconIndex = this.$refs.crud.findColumnIndex('menuIcon')
        const externalIndex = this.$refs.crud.findColumnIndex('external')
        const externalUrlIndex = this.$refs.crud.findColumnIndex('externalUrl')
        if (newValue === 1) {
          // 顶级菜单
          // 新建弹出框
          this.option.column[pidIndex].addDisplay = false
          this.option.column[menuIconIndex].addDisplay = true
          this.option.column[externalIndex].addDisplay = true
          this.option.column[componentNameIndex].addDisplay = false
          if (this.form.external) {
            this.option.column[externalUrlIndex].addDisplay = true
          } else {
            this.option.column[externalUrlIndex].addDisplay = false
            this.form.externalUrl = ''
          }
          // 编辑弹出框
          this.option.column[pidIndex].editDisplay = false
          this.option.column[menuIconIndex].editDisplay = true
          this.option.column[externalIndex].editDisplay = true
          this.option.column[componentNameIndex].editDisplay = false
          if (this.form.external) {
            this.option.column[externalUrlIndex].editDisplay = true
          } else {
            this.option.column[externalUrlIndex].editDisplay = false
            this.form.externalUrl = ''
          }
        } else if (newValue === 2) {
          // 新建弹出框
          this.option.column[pidIndex].addDisplay = true
          this.option.column[menuIconIndex].addDisplay = true
          this.option.column[externalIndex].addDisplay = true
          if (this.form.external) {
            this.option.column[externalUrlIndex].addDisplay = true
            this.option.column[componentNameIndex].addDisplay = false
            this.form.componentName = ''
          } else {
            this.option.column[externalUrlIndex].addDisplay = false
            this.option.column[componentNameIndex].addDisplay = true
            this.form.externalUrl = ''
          }
          // 编辑弹出框
          this.option.column[pidIndex].editDisplay = true
          this.option.column[menuIconIndex].editDisplay = true
          this.option.column[externalIndex].editDisplay = true
          if (this.form.external) {
            this.option.column[externalUrlIndex].editDisplay = true
            this.option.column[componentNameIndex].editDisplay = false
            this.form.componentName = ''
          } else {
            this.option.column[externalUrlIndex].editDisplay = false
            this.option.column[componentNameIndex].editDisplay = true
            this.form.externalUrl = ''
          }
        } else if (newValue === 3) {
          // 新建弹出框
          this.option.column[pidIndex].addDisplay = true
          this.option.column[componentNameIndex].addDisplay = false
          this.option.column[menuIconIndex].addDisplay = false
          this.option.column[externalIndex].addDisplay = false
          this.option.column[externalUrlIndex].addDisplay = false
          // 编辑弹出框
          this.option.column[pidIndex].editDisplay = true
          this.option.column[componentNameIndex].editDisplay = false
          this.option.column[menuIconIndex].editDisplay = false
          this.option.column[externalIndex].editDisplay = false
          this.option.column[externalUrlIndex].editDisplay = false
          // 设置默认数据值
          this.form.componentName = ''
          this.form.menuIcon = ''
          this.form.external = false
          this.form.externalUrl = ''
        }
      },
      deep: true
    },
    'form.external': {
      handler (newValue, oldValue) {
        const externalUrlIndex = this.$refs.crud.findColumnIndex('externalUrl')
        const componentNameIndex = this.$refs.crud.findColumnIndex('componentName')
        if (newValue) {
          // 设置默认值
          this.form.componentName = ''
          // 新增弹出框
          this.option.column[externalUrlIndex].addDisplay = true
          this.option.column[componentNameIndex].addDisplay = false
          // 编辑弹出框
          this.option.column[externalUrlIndex].editDisplay = true
          this.option.column[componentNameIndex].editDisplay = false
        } else {
          // 设置默认值
          this.form.externalUrl = ''
          this.option.column[externalUrlIndex].addDisplay = false
          this.option.column[externalUrlIndex].editDisplay = false
          if (this.form.menuType === 1) {
            // 非顶级菜单
            this.form.componentName = ''
            this.option.column[componentNameIndex].addDisplay = false
            this.option.column[componentNameIndex].editDisplay = false
          } else if (this.form.menuType === 2) {
            this.option.column[componentNameIndex].addDisplay = true
            this.option.column[componentNameIndex].editDisplay = true
          } else if (this.form.menuType === 3) {
            this.form.componentName = ''
            this.option.column[componentNameIndex].addDisplay = false
            this.option.column[componentNameIndex].editDisplay = false
          }
        }
      },
      deep: true
    }
  },
  mounted () {
    this.fetchParentMenuTree()
    this.fetchRouteComponentNames()
    this.fetchIconfonts()
    const menuTypeIndex = this.$refs.crud.findColumnIndex('menuType')
    this.option.column[menuTypeIndex].dicData = this.menuTypeDicData1
  },
  methods: {
    fetchParentMenuTree () {
      this.$store.dispatch(getSysRoleMenuListAction, { filterButtonPermission: true }).then((res) => {
        const resCode = res.code
        const errorMsg = res.message
        if (resCode === 0) {
          const index = this.$refs.crud.findColumnIndex('pid')
          this.option.column[index].dicData = res.data
        } else {
          this.$message({
            type: 'error',
            showClose: true,
            message: errorMsg || '查询菜单数据失败,请稍后再试!'
          })
        }
      }).catch((err) => {
        console.log(err)
        this.$message({
          type: 'error',
          showClose: true,
          message: '查询菜单数据异常,请稍后再试!'
        })
      })
    },
    fetchRouteComponentNames () {
      const routes = this.$router.options.routes
      const index = this.$refs.crud.findColumnIndex('componentName')
      this.option.column[index].dicData = routes
    },
    fetchIconfonts () {
      Promise.all([
        this.$store.dispatch(listElementIconsAction),
        this.$store.dispatch(listIconFontIconsAction)
      ]).then((res) => {
        const [elementIcons, iconfontIcons] = res
        const index = this.$refs.crud.findColumnIndex('menuIcon')
        const elements = elementIcons.map((i) => {
          return i.name
        })
        const iconfonts = iconfontIcons.map((i) => {
          return 'iconfont ' + i.name
        })
        this.option.column[index].iconList[0].list = elements
        this.option.column[index].iconList[1].list = iconfonts
      }).catch((err) => {
        console.log(err)
        this.$message({
          type: 'error',
          showClose: true,
          message: '查询菜单数据异常,请稍后再试!'
        })
      })
    },
    handleAddSubMenu (row) {
      this.addSubMenu = true
      this.addSubMenuRow = row
      this.$refs.crud.rowAdd()
    },
    onChangeMenuType (data) {
      console.log(data)
    },
    rowStyle ({ row, column, rowIndex }) {
      return {}
    },
    cellStyle ({ row, column, rowIndex, columnIndex }) {
      // return {
      //   color: 'green',
      //   fontWeight: 'bold',
      //   fontSize: '20'
      // }
      return {}
    },
    rowSave (row, loading, done) {
      loading()
      this.$store.dispatch(addSysMenuAction, row).then((res) => {
        done()
        const resCode = res.code
        const errorMsg = res.message
        if (resCode === 0) {
          this.onLoad(this.page)
          this.$message({
            type: 'success',
            message: '保存操作成功!'
          })
        } else {
          this.$message({
            type: 'error',
            showClose: true,
            message: errorMsg || '保存数据失败,请稍后再试!'
          })
        }
      }, (error) => {
        done()
        console.log(error)
      })
    },
    rowUpdate (row, index, loading, done) {
      loading()
      this.$store.dispatch(updateSysMenuAction, row).then((res) => {
        done()
        const resCode = res.code
        const errorMsg = res.message
        if (resCode === 0) {
          this.onLoad(this.page)
          this.$message({
            type: 'success',
            message: '编辑操作成功!'
          })
        } else {
          this.$message({
            type: 'error',
            showClose: true,
            message: errorMsg || '编辑数据失败,请稍后再试!'
          })
        }
      }, (error) => {
        done()
        console.log(error)
      })
    },
    rowDel (row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.loading = true
          const idParams = { id: row.id }
          return this.$store.dispatch(removeSysMenuAction, idParams)
        })
        .then((res) => {
          this.loading = false
          const resCode = res.code
          const errorMsg = res.message
          if (resCode === 0) {
            this.onLoad(this.page)
            this.$message({
              type: 'success',
              message: '删除操作成功!'
            })
          } else {
            this.loading = false
            this.$message({
              type: 'error',
              showClose: true,
              message: errorMsg || '删除数据失败,请稍后再试!'
            })
          }
        })
    },
    handleDelete () {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据')
        return
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.loading = true
          const idParams = { ids: this.ids }
          return this.$store.dispatch(removeSysMenusAction, idParams)
        })
        .then((res) => {
          this.loading = false
          const resCode = res.code
          const errorMsg = res.message
          if (resCode === 0) {
            this.$message({
              type: 'success',
              message: '批量删除操作成功!'
            })
            this.onLoad(this.page)
            this.$refs.crud.toggleSelection()
          } else {
            this.loading = false
            this.$message({
              type: 'error',
              showClose: true,
              message: errorMsg || '批量删除数据失败,请稍后再试!'
            })
          }
        })
    },
    rowClick (row, event, column) {
      this.$refs.crud.rowView(row, column)
    },
    refresh ({ page, searchForm }) {
      this.onLoad(page)
    },
    beforeOpen (done, type) {
      const menuTypeIndex = this.$refs.crud.findColumnIndex('menuType')
      const pidIndex = this.$refs.crud.findColumnIndex('pid')
      const menuType = this.addSubMenuRow.menuType
      if (this.addSubMenu) {
        // 上级菜单
        this.option.column[pidIndex].disabled = true
        this.form.pid = this.addSubMenuRow.id
        if (menuType === 1) {
          // 顶级菜单
          this.option.column[menuTypeIndex].dicData = this.menuTypeDicData1
          this.form.menuType = 1
        } else if (menuType === 2) {
          this.option.column[menuTypeIndex].dicData = this.menuTypeDicData2
          this.form.menuType = 2
        }
      } else {
        this.option.column[pidIndex].disabled = false
        this.option.column[menuTypeIndex].dicData = this.menuTypeDicData1
      }
      // 获取对应的该菜单数据
      this.option.column[menuTypeIndex].disabled = false
      if (['edit', 'view'].includes(type)) {
        this.option.column[menuTypeIndex].disabled = true
        const idParams = { id: this.form.id }
        this.$store.dispatch(getSysMenuByIdAction, idParams).then((res) => {
          const resCode = res.code
          const errorMsg = res.message
          if (resCode === 0) {
            this.form = res.data
          } else {
            this.$message({
              type: 'error',
              showClose: true,
              message: errorMsg || '查询数据失败,请稍后再试!'
            })
          }
        }).catch((err) => {
          console.log(err)
          this.$message({
            type: 'error',
            showClose: true,
            message: '查询数据异常,请稍后再试!'
          })
        })
      }
      this.addSubMenu = false
      done()
    },
    // 20200202 Walter: 修复type类型显示错误
    beforeClose (done, type) {
      if (['add'].includes(type)) {
        const menuTypeIndex = this.$refs.crud.findColumnIndex('menuType')
        this.option.column[menuTypeIndex].dicData = this.menuTypeDicData1
      }
      done()
    },
    searchReset () {
      this.query = {}
      this.onLoad(this.page)
    },
    searchChange (params, done) {
      done()
      this.query = params
      this.page.currentPage = 1
      this.onLoad(this.page, params)
    },
    selectionChange (list) {
      this.selectionList = list
    },
    selectionClear () {
      this.selectionList = []
      this.$refs.crud.toggleSelection()
    },
    currentChange (currentPage) {
      this.page.currentPage = currentPage
    },
    sizeChange (pageSize) {
      this.page.pageSize = pageSize
    },
    onLoad (page, params = {}) {
      this.loading = true
      let queryData = {
        pageNo: page.currentPage,
        pageSize: page.pageSize
      }
      queryData = Object.assign(queryData, Object.assign(params, this.query))
      this.$store.dispatch(getSysMenuPageListAction, queryData).then((res) => {
        this.loading = false
        const resCode = res.code
        const errorMsg = res.message
        if (resCode === 0) {
          const data = res.data
          this.page.total = parseInt(data.total)
          this.data = data.records
          this.selectionClear()
        } else {
          this.$message({
            type: 'error',
            showClose: true,
            message: errorMsg || '查询数据失败,请稍后再试!'
          })
        }
      }).catch((err) => {
        console.log(err)
        this.$message({
          type: 'error',
          showClose: true,
          message: '查询数据异常,请稍后再试!'
        })
      })
    }
  },
  head () {
    return {
      title: '菜单管理 | ' + this.website.name,
      meta: [
        { hid: 'description', name: 'description', content: '菜单管理' }
      ]
    }
  }
}
</script>

<style>
</style>
